const Framework = require("../../framework/node-core-framework.js");

module.exports = {
    "POST /user/login": async (ctx) => {

        const { sn_code, device_id } = ctx.getBody();

        const { pla_account,device_status} = await Framework.getModels();

        // 获取用户信息
    
        const user = await pla_account.findOne({ where: { sn_code } });
        if (!user) {
            return ctx.fail('用户不存在');
        }

        // 更新设备状态
  
        const device = await device_status.findOne({ where: { sn_code } });
        if (device) {
            await device_status.update({
                device_id: device_id
            }, { where: { sn_code } });
        } else {
            await device_status.create({
                sn_code: sn_code,
                device_id: device_id
            });
        }


        const token = Framework.getServices().tokenService.create({
            sn_code: user.sn_code,
            device_id: user.device_id
        });

        return ctx.success({ token, user: user.toJSON() });

    }
}